$(document).ready((function(){	
    // Oculta as DIVs aonde serão exibidos os resultados das querys
    $(".results").hide();
    $(".content").hide();
    
    // Submeti a consulta para que ela seja executada no servlet (ExecuteQueryJenaServlet)
    // Além disso, caso a requisição seja bem sucedida é apresentada ao usuário uma tabela com os resultado da consulta.
    $("#submitRun").click(function(){
        if($("textarea[id=assembleQuery]").val().length > 0){
            $("#submitRun").attr('disabled', true);
            
            $(".results").show();
            $(".content").show();
            $(".content").html("<b>Please wait...</b>&nbsp;&nbsp;<img src=\"./images/ajax-loader.gif\"/>");
            
            $.ajax({
                url: "execute-query",
                type: "GET",
                data: {
                    "queryString" : $("textarea[id=assembleQuery]").val(),
                    "endpoint" : $("input[id=endpoint]").val()
                },
                dataType: "xml",
                error:function(xml){
                    console.log(xml);
                    // Reativa o botão do submit
                    $("#submitRun").attr("disabled", false);
                },
                success:function(xml){
                    $(".content").html("");
                    // Reativa o botão do submit
                    $("#submitRun").attr("disabled", false); 
                    
                    var table = $("<table cellspacing=\"1\" id=\"tablesorter\" class=\"display\">"),
                    thead = $("<thead>"),
                    rowsTHead = $("<tr>"),
                    tbody = $("<tbody>"),
                    numberOfColumns,
                    varsQuery = [];
                    
                    // Cabeçalho da tabela
                    $(xml).find("head").each(function(){
                        var variable = $(this).find("variable");
                        numberOfColumns = variable.length;
                        for (var i = 0; i < variable.length; i++){
                            var name = $(variable[i]).attr("name");
                            varsQuery.push(name);
                            rowsTHead.append($("<th>").html(name));
                        }
                    });
                    thead.append(rowsTHead);
                    
                    // Corpo da tabela
                    $(xml).find("result").each(function(){
                        var binding = $(this).find("binding"),
                        sonBinding = $(binding).children();
                        
                        var i = 0,
                        sizeBinding = binding.length - 1;
                        
                        var rowsTBody = $("<tr>");
                        sonBinding.length = numberOfColumns;
                           
                        for (var j = 0; j < sonBinding.length; j++){
                            var tdBody = $("<td>");
                            if ($(binding[i]).attr("name") === varsQuery[j]){
                                tdBody.html($(sonBinding[i]).text());
                                if (i < sizeBinding){
                                    i++;
                                } else {
                                    i--;
                                }
                            } else {
                                tdBody.html("");
                            }
                            rowsTBody.append(tdBody);
                        }
                        tbody.append(rowsTBody);
                    });
                    
                    table.append(thead).append(tbody);
                    
                    $(".content").html(table);
                    
                    $("#tablesorter").dataTable({
                        "bPaginate": true,
                        "bJQueryUI": false,
                        "sPaginationType": "full_numbers",
                        "bDestroy": true
                    });
                }
            });
        }
    });
}));